<template>
  <div class="opening-guidance-and-insurance-report">
    <!-- 顶部筛选区域 -->
    <el-card class="filter-card">
      <div class="filter-header">
        <span class="filter-title">筛选条件</span>
        <el-button-group class="filter-actions">
          <el-button size="small" type="primary" @click="handleSearch">查询</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
        </el-button-group>
      </div>
      <el-form :model="queryForm" label-width="80px" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="queryForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="管理区域">
              <el-select v-model="queryForm.regionId" placeholder="选择区域" size="small" style="width: 100%">
                <el-option label="全部区域" value="" />
                <el-option
                  v-for="item in managementAreaOptions"
                  :key="item.enCode"
                  :label="item.fullName"
                  :value="item.enCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="加盟品牌">
              <el-select v-model="queryForm.brandId" placeholder="选择品牌" size="small" style="width: 100%">
                <el-option label="全部品牌" value="" />
                <el-option
                  v-for="item in brandOptions"
                  :key="item.enCode"
                  :label="item.fullName"
                  :value="item.enCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="校区状态">
              <el-select v-model="queryForm.campusStatus" placeholder="选择状态" size="small" style="width: 100%">
                <el-option label="全部状态" value="" />
                <el-option
                  v-for="item in campusStatusOptions"
                  :key="item.enCode"
                  :label="item.fullName"
                  :value="item.enCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="快速选择">
              <el-button-group size="small" style="width: 100%">
                <el-button @click="setQuickDate('today')">今天</el-button>
                <el-button @click="setQuickDate('week')">本周</el-button>
                <el-button @click="setQuickDate('month')">本月</el-button>
                <el-button @click="setQuickDate('quarter')">本季度</el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据展示区域 -->
    <el-row :gutter="20" class="report-content">
      <!-- 左侧：校区开业辅导统计 -->
      <el-col :span="12">
        <opening-guidance-report ref="openingGuidanceReport" :query-form="queryForm" @loading="handleLoading" @export="handleExport"></opening-guidance-report>
      </el-col>

      <!-- 右侧：保险购买统计 -->
      <el-col :span="12">
        <insurance-report ref="insuranceReport" :query-form="queryForm" @loading="handleLoading" @export="handleExport"></insurance-report>
      </el-col>
    </el-row>

    <!-- 底部汇总信息 -->
    <el-card class="summary-card">
      <div class="summary-header">
        <span class="summary-title">数据汇总</span>
        <el-button-group class="summary-actions">
          <el-button size="small" icon="el-icon-document" @click="exportSummaryReport">导出汇总报告</el-button>
          <el-button size="small" icon="el-icon-printer" @click="printReport">打印报告</el-button>
        </el-button-group>
      </div>
      <el-row :gutter="20" class="summary-content">
        <el-col :span="6">
          <div class="summary-item">
            <div class="summary-label">总校区数</div>
            <div class="summary-value">{{ summaryData.totalCampusCount }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-item">
            <div class="summary-label">辅导完成率</div>
            <div class="summary-value">{{ summaryData.guidanceCompletionRate }}%</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-item">
            <div class="summary-label">保险购买率</div>
            <div class="summary-value">{{ summaryData.insurancePurchaseRate }}%</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-item">
            <div class="summary-label">即将到期保险</div>
            <div class="summary-value">{{ summaryData.expiringInsuranceCount }}</div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import OpeningGuidanceReport from '@/views/report/components/OpeningGuidanceReport.vue'
import InsuranceReport from '@/views/report/components/InsuranceReport.vue'
// 引入数据字典常量与获取方法
import { DICTIONARY_TYPES, getEnabledDictionaryData } from '@/utils/dictionaryConstants'

export default {
  name: 'OpeningGuidanceAndInsuranceReport',

  components: {
    OpeningGuidanceReport,
    InsuranceReport
  },

  data() {
    return {
      // 查询表单
      queryForm: {
        dateRange: [],
        startDate: '',
        endDate: '',
        regionId: '',
        brandId: '',
        campusStatus: ''
      },

      // 汇总数据
      summaryData: {
        totalCampusCount: 0,
        guidanceCompletionRate: 0,
        insurancePurchaseRate: 0,
        expiringInsuranceCount: 0
      },

      // 字典选项
      managementAreaOptions: [],
      brandOptions: [],
      campusStatusOptions: [],

      // 加载状态
      loading: false
    }
  },

  mounted() {
    // 设置默认时间范围为本月
    this.setQuickDate('month')
    // 加载筛选所需数据字典
    this.loadFilterDictionaries()
    this.loadSummaryData()
  },

  methods: {
    /**
     * 加载筛选区域的数据字典（管理区域、品牌、校区状态）
     * - 使用启用状态字典以避免展示已禁用条目
     * - 失败时提示并回退为空数组
     */
    async loadFilterDictionaries() {
      try {
        // 管理区域（公司）
        this.managementAreaOptions = await getEnabledDictionaryData(DICTIONARY_TYPES.COMPANY)
      } catch (error) {
        console.error('加载管理区域字典失败:', error)
        this.managementAreaOptions = []
        this.$message.error('管理区域选项加载失败')
      }

      try {
        // 校区品牌
        this.brandOptions = await getEnabledDictionaryData(DICTIONARY_TYPES.BRAND)
      } catch (error) {
        console.error('加载品牌字典失败:', error)
        this.brandOptions = []
        this.$message.error('加盟品牌选项加载失败')
      }

      try {
        // 校区状态
        this.campusStatusOptions = await getEnabledDictionaryData(DICTIONARY_TYPES.CAMPUS_STATUS)
      } catch (error) {
        console.error('加载校区状态字典失败:', error)
        this.campusStatusOptions = []
        this.$message.error('校区状态选项加载失败')
      }
    },
    /**
     * 设置快速日期
     */
    setQuickDate(type) {
      const end = new Date()
      const start = new Date()

      switch (type) {
        case 'today':
          // 今天
          break
        case 'week':
          start.setDate(start.getDate() - 7)
          break
        case 'month':
          start.setDate(1)
          break
        case 'quarter':
          const quarter = Math.floor(end.getMonth() / 3)
          start.setMonth(quarter * 3)
          start.setDate(1)
          break
      }

      this.queryForm.dateRange = [start, end]
      this.queryForm.startDate = this.formatDate(start)
      this.queryForm.endDate = this.formatDate(end)
    },

    /**
     * 格式化日期
     */
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    /**
     * 查询数据
     */
    handleSearch() {
      // 验证日期范围
      if (this.queryForm.startDate && this.queryForm.endDate) {
        const start = new Date(this.queryForm.startDate)
        const end = new Date(this.queryForm.endDate)
        if (start > end) {
          this.$message.warning('开始日期不能晚于结束日期')
          return
        }
      }

      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        this.queryForm.startDate = this.formatDate(this.queryForm.dateRange[0])
        this.queryForm.endDate = this.formatDate(this.queryForm.dateRange[1])
      }

      // 刷新子组件数据
      this.$refs.openingGuidanceReport && this.$refs.openingGuidanceReport.loadData()
      this.$refs.insuranceReport && this.$refs.insuranceReport.loadData()
      this.loadSummaryData()
    },

    /**
     * 重置查询条件
     */
    handleReset() {
      this.queryForm = {
        dateRange: [],
        startDate: '',
        endDate: '',
        regionId: '',
        brandId: '',
        campusStatus: ''
      }
      // 重置日期快捷选项
      this.dateRange = ''
      this.setQuickDate('month')
      this.handleSearch()
    },

    /**
     * 加载汇总数据
     */
    async loadSummaryData() {
      try {
        // 模拟API调用，实际使用时替换为真实API
        // const response = await this.$http.get('/api/report/summary', {
        //   params: this.queryForm
        // })

        // 模拟数据
        setTimeout(() => {
          this.summaryData = {
            totalCampusCount: 156,
            guidanceCompletionRate: 87,
            insurancePurchaseRate: 92,
            expiringInsuranceCount: 12
          }
        }, 300)
      } catch (error) {
        console.error('加载汇总数据失败：', error)
      }
    },

    /**
     * 处理加载状态
     */
    handleLoading(loading) {
      this.loading = loading
    },

    /**
     * 处理导出
     */
    handleExport(exportData) {
      this.$emit('export', exportData)
    },

    /**
     * 导出汇总报表
     */
    exportSummaryReport() {
      // 获取两个子组件的数据
      const openingData = this.$refs.openingGuidanceReport && this.$refs.openingGuidanceReport.getExportData()
      const insuranceData = this.$refs.insuranceReport && this.$refs.insuranceReport.getExportData()

      const exportData = {
        openingGuidance: openingData,
        insurance: insuranceData,
        summary: this.summaryData,
        exportTime: this.formatDateTime(new Date()),
        queryConditions: {
          startDate: this.queryForm.startDate,
          endDate: this.queryForm.endDate,
          regionId: this.queryForm.regionId,
          brandId: this.queryForm.brandId,
          campusId: this.queryForm.campusId
        }
      }

      this.$emit('export', {
        type: 'opening_guidance_and_insurance_summary',
        data: exportData
      })

      this.$message.success('正在导出综合报表...')
    },

    /**
     * 打印报告
     */
    printReport() {
      // 添加打印样式
      const printStyles = `
        <style type="text/css" media="print">
          .report-actions { display: none !important; }
          .header-actions { display: none !important; }
          .el-dialog__wrapper { display: none !important; }
          body { margin: 0; padding: 20px; }
        </style>
      `
      document.head.insertAdjacentHTML('beforeend', printStyles)

      // 打印完成后移除样式
      setTimeout(() => {
        const styleElement = document.querySelector('style[media="print"]')
        if (styleElement) {
          styleElement.remove()
        }
      }, 1000)

      window.print()
    },

    /**
     * 格式化日期时间
     */
    formatDateTime(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.opening-guidance-and-insurance-report {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .filter-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }

  .filter-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }

  .filter-actions {
    display: flex;
    gap: 10px;
  }

  .filter-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .report-content {
    margin-bottom: 20px;
  }

  .summary-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }

  .summary-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }

  .summary-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }

  .summary-actions {
    display: flex;
    gap: 10px;
  }

  .summary-content {
    text-align: center;
  }

  .summary-item {
    padding: 15px;
    background: #f5f7fa;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      background: #e6f2ff;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .summary-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .summary-value {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
  }

  // 响应式设计
  @media (max-width: 1200px) {
    .report-content {
      .el-col {
        margin-bottom: 20px;
      }
    }
  }

  @media (max-width: 768px) {
    .filter-form {
      .el-col {
        margin-bottom: 10px;
      }
    }

    .summary-content {
      .el-col {
        margin-bottom: 15px;
      }
    }
  }
}
</style>
